package org.jin.jinaicode.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.jin.jinaicode.ai.model.HtmlCodeResult;
import org.jin.jinaicode.ai.model.MultiFileCodeResult;
import org.jin.jinaicode.model.enums.CodeGenTypeEnum;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * 文件保存器
 */
@Deprecated
public class CodeFileSaver {

    // 文件保存的根目录
    private static final String FILE_SAVE_ROOT_PATH = System.getProperty("user.dir") + "/tmp/code_output";

    // 保存HTML多文件代码
    public static File saveHtmlCode(HtmlCodeResult htmlCode){
        String baseDirPath = buildUniqueFilePath(CodeGenTypeEnum.HTML.getValue());
        saveFile(baseDirPath, "index.html", htmlCode.getHtmlCode());
        return new File(baseDirPath);
    }

    // 保存多文件代码
    public static File saveMultiFileCode(MultiFileCodeResult multiFileCodeResult){
        String baseDirPath = buildUniqueFilePath(CodeGenTypeEnum.MULTI_FILE.getValue());
        saveFile(baseDirPath, "index.html", multiFileCodeResult.getHtmlCode());
        saveFile(baseDirPath, "style.css", multiFileCodeResult.getCssCode());
        saveFile(baseDirPath, "script.js", multiFileCodeResult.getJsCode());
        return new File(baseDirPath);
    }

    // 构建文件唯一路径（tmp/code_output/bizType_雪花ID）
    private static String buildUniqueFilePath(String bizType){
        String uniqueFilePath = StrUtil.format("{}_{}",bizType,IdUtil.getSnowflakeNextIdStr());
        String dirPath = FILE_SAVE_ROOT_PATH + File.separator + uniqueFilePath;
        FileUtil.mkdir(dirPath);
        return dirPath;

    }

    //保存单个文件
    private static void saveFile(String dirPath, String fileName, String content){
        String filePath = dirPath + File.separator + fileName;
        FileUtil.writeString(content, filePath, StandardCharsets.UTF_8);
    }
}
